package com.chenfan.ccp.util.sign;


import com.chenfan.ccp.util.start.ApplicationContextUtil;
import com.chenfan.ccp.utils.sign.SignUtil;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ConfigPropertiesUtil {
    public static final String UPLOAD_FILE_NAME = "uploadFile-%s.properties";
    public static final String PROJECT_FILE_NAME = "$project-%s.properties";
    private static final String FILE_SUFFIX = "test";

    private ConfigPropertiesUtil() {

    }

    public static void addUploadFileProperties(Map<String, String> param, String fileName, String userName, String userPass) {
        addProperties(param, fileName, SignUtil.Type.Blow, userName, userPass);
    }

    private static void addProperties(Map<String, String> param, String fileName, SignUtil.Type type, String userName, String userPass) {

        Map<String, String> encryptParam = new HashMap(getProperties(fileName, type));
        for (Map.Entry<String, String> entry : param.entrySet()) {
            encryptParam.put(entry.getKey(), SignUtil.encrypt(entry.getValue(), type));
        }
        ConfigGitUtil.getInstance().addParam(encryptParam, fileName, userName, userPass);
    }

    public static void addProjectProperties(Map<String, String> param, String fileName, String userName, String userPass) {
        addProperties(param, fileName, SignUtil.Type.Rc4, userName, userPass);
    }

    private static Properties getProperties(String fileName, SignUtil.Type type) {

        Properties properties = new Properties();
        try {
            properties.load(ConfigGitUtil.getInstance().getResource(fileName).getInputStream());
            Enumeration<?> enumeration = properties.propertyNames();
            while (enumeration.hasMoreElements()) {
                String key = (String) enumeration.nextElement();

                properties.setProperty(key, SignUtil.decrypt(properties.getProperty(key), type));
            }

        } catch (Exception e) {

        }
        return properties;
    }


    public static Properties getUploadFileProperties() {

        return getProperties(getUploadFileName(), SignUtil.Type.Blow);
    }


    public static Properties getProjectProperties() {

        return getProperties(getProjectFileName(), SignUtil.Type.Rc4);
    }

    private static String getUploadFileName() {
        return String.format(UPLOAD_FILE_NAME, ApplicationContextUtil.
                getProfile().isEmpty() ? FILE_SUFFIX : ApplicationContextUtil.getProfile());
    }

    private static String getProjectFileName() {
        return String.format(PROJECT_FILE_NAME, ApplicationContextUtil.
                getProfile().isEmpty() ? FILE_SUFFIX : ApplicationContextUtil.getProfile());
    }


}
